package com.example.whereismystuff.views;

import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.example.whereismystuff.R;
import com.example.whereismystuff.classes.Item;
import com.example.whereismystuff.classes.ItemDataBaseAdapter;
import com.example.whereismystuff.classes.LoginDataBaseAdapter;
import com.example.whereismystuff.classes.User;
import com.example.whereismystuff.classes.UserDataManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

/**
 * Edit item view is in charge of displaying the information of the current item clicked while also
 * allowing the user to change the information if needed.
 * @author NullPointers
 *
 */
public class EditItem extends Activity {
	private boolean imageClicked;
	private Button save, editImage;
	private EditText e_itemName, e_itemDescription, e_zipCode; 
	private RadioButton found, lost;
	private CheckBox tagElectronic, tagBook, tagPersonal;
	private RadioGroup rdbGp1;
	private final int MIN_STRING_LENGTH = 0;
	private final int TAGS_LENGTH = 3;
	private final int SELECT_ID = 0;
	private String itemName, itemDescription, foundString, username, zipCode, tempItemName, id;
	private AlertDialog.Builder alertDialog;
	private ArrayList<String> tags;
	private Item item;
	private Intent i;
	private Uri outputFileUri;
	private Bitmap bitmap;

	ItemDataBaseAdapter itemDataBaseAdapter;

	private final String DIALOG_MSG = "Please Input a Name";
	private ImageView imageView;

	/**
	 * Method used to Instantiate Object and set the Layout for the Activity
	 * @param Bundle
	 */
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit);

		itemDataBaseAdapter=new ItemDataBaseAdapter(this);
		itemDataBaseAdapter=itemDataBaseAdapter.open();

		imageView = (ImageView) findViewById(R.id.imageView1);

		editImage = (Button) findViewById(R.id.editImageButton);
		editImage.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
				root.mkdirs();
				//	final String fname = Utils.getUniqueImageFilename();
				//	final File sdImageMainDirectory = new File(root, fname);
				//	outputFileUri = Uri.fromFile(sdImageMainDirectory);

				// Camera.
				final List<Intent> cameraIntents = new ArrayList<Intent>();
				final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				final PackageManager packageManager = getPackageManager();
				final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
				for(ResolveInfo res : listCam) {
					final String packageName = res.activityInfo.packageName;
					final Intent intent = new Intent(captureIntent);
					intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
					intent.setPackage(packageName);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
					cameraIntents.add(intent);
				}

				// Filesystem.
				final Intent galleryIntent = new Intent();
				galleryIntent.setType("image/*");
				galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

				// Chooser of filesystem options.
				final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

				// Add the camera options.
				chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

				startActivityForResult(chooserIntent, SELECT_ID);
			}
		});


		save = (Button) findViewById(R.id.save);
		e_itemName = (EditText) findViewById(R.id.itemName);
		e_itemDescription = (EditText) findViewById(R.id.itemDescription);
		e_zipCode = (EditText) findViewById(R.id.e_zipCode);
		tagElectronic = (CheckBox) findViewById(R.id.e_isElectronic);
		tagBook = (CheckBox) findViewById(R.id.e_isBook);
		tagPersonal = (CheckBox) findViewById(R.id.e_isPersonal);
		alertDialog = new AlertDialog.Builder(this);
		found = (RadioButton) findViewById(R.id.found);
		lost = (RadioButton) findViewById(R.id.lost);
		tags = new ArrayList<String>();
		rdbGp1 = (RadioGroup) findViewById(R.id.rdbGp1);
		Bundle extras = getIntent().getExtras();
		if(extras != null){
			if(extras.getString("ItemName") != null){
				itemName = extras.getString("ItemName");
				tempItemName = extras.getString("ItemName");
			}
			if(extras.getString("Description") != null) {
				itemDescription = extras.getString("Description");
			}

			if(extras.getString("Found") != null){
				foundString = extras.getString("Found");
			}
			if(extras.getString("ZipCode") != null){
				zipCode = extras.getString("ZipCode");
				e_zipCode.setText(zipCode);
			}
			if(extras.getString("Image") != null){
				String outputBitmap = extras.getString("Image");
				imageView.setImageBitmap(decodeBitmap(outputBitmap, 200, 200));
			}
			if(extras.getString("Username") != null){
				username = extras.getString("Username");
			}
			if(extras.getString("Book") != null){
				if(extras.getString("Book").equals("true")){
					tagBook.setChecked(true);
				}
			}
			if(extras.getString("Electronic") != null){
				if(extras.getString("Electronic").equals("true")){
					tagElectronic.setChecked(true);
				}
			}
			if(extras.getString("Personal") != null){
				if(extras.getString("Personal").equals("true")){
					tagPersonal.setChecked(true);
				}
			}
			id = extras.getString("id");

		}
		String id = extras.getString("id");
		e_itemName.setText(itemName);
		e_itemDescription.setText(itemDescription);
		if(foundString.equals("true")) {
			((CompoundButton) rdbGp1.getChildAt(0)).setChecked(true);
		}
		else
			((CompoundButton) rdbGp1.getChildAt(1)).setChecked(true);
	}
	public static Bitmap decodeBitmap(String id,
			int width, int height) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(id, options);

		// Calculate inSampleSize
		options.inSampleSize = calcSize(options, width, height);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(id, options);
	}

	public static int calcSize(BitmapFactory.Options options, int width, int height) {
		final int tempHeight = options.outHeight;
		final int tempWidth = options.outWidth;
		int size = 2;

		if (tempHeight > height || tempWidth > width) {
			if (tempWidth > tempHeight) {
				size = Math.round((float)tempHeight / (float)height);
			} else {
				size = Math.round((float)tempWidth / (float)width);
			}
		}
		return size;
	}
	/**
	 * Allows the user to add an image to the item
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		if(resultCode == RESULT_OK){
			Uri selectedImageUri = null;
			if(requestCode == SELECT_ID){
				final boolean isCamera;
				if(data == null){
					isCamera = true;
				}
				else{
					final String action = data.getAction();
					if(action == null){
						isCamera = false;
					}
					else{
						isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					}
				}

				if(isCamera){
					selectedImageUri = outputFileUri;
				}
				else{
					selectedImageUri = data == null ? null : data.getData();
				}
			}
			try {
				imageClicked = true;
				imageView.setMaxWidth(200);
				imageView.setMaxHeight(200);
				imageView.setImageURI(selectedImageUri);
				outputFileUri = selectedImageUri;
			}
			catch (Exception e) {};
		}
	}

	/**
	 * This method corresponds to when the save button is pressed. It saves all of the current data
	 * in the ciew back into the database by updating the entry.
	 * @param v
	 */
	public void onSave(View v){
		Date now = new Date();
		itemName = e_itemName.getText().toString();
		zipCode = e_zipCode.getText().toString();
		itemDescription = e_itemDescription.getText().toString();
		setUpTags();
		foundString = String.valueOf(found.isChecked());
		if(itemName.length() == MIN_STRING_LENGTH){
			alertDialog.setMessage(DIALOG_MSG);
			alertDialog.setNeutralButton("Ok",
					new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {}});
			alertDialog.show();
		} else {
			if(imageClicked) 
				itemDataBaseAdapter.updateEntry(username, itemName, itemDescription, DateFormat.getDateTimeInstance(
						DateFormat.SHORT, DateFormat.SHORT).format(now), foundString, tags, null, zipCode, tempItemName, id, getPath(outputFileUri));
			else
				itemDataBaseAdapter.updateEntry(username, itemName, itemDescription, DateFormat.getDateTimeInstance(
						DateFormat.SHORT, DateFormat.SHORT).format(now), foundString, tags, null, zipCode, tempItemName, id);

			try{
				Class c = Class.forName("com.example.whereismystuff.views.ItemViewer");
				//Bundle extras = new Bundle();
				Bundle extras = getIntent().getExtras();
				i = new Intent(getApplicationContext(), c);
				//extras.putString("Username", username);
				//i.putExtras(extras);
				i.putExtras(extras);
				startActivity(i);
			} catch (ClassNotFoundException e){
				e.printStackTrace();
			}
		}
	}

	public String getPath(Uri uri)  
	{ 
		Cursor cursor = getContentResolver().query(uri, null, null, null, null);
		cursor.moveToFirst();
		int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
		return cursor.getString(idx);
	} 
	/**
	 * This method corresponds to when the user presses the cancel buton. It redirects the user back to the itemviewer
	 * along with the original bundle form the intent so itemviewer knows what items to display
	 * @param v
	 */
	public void onCancel(View v){
		try{
			Class c = Class.forName("com.example.whereismystuff.views.ItemViewer");
			i = getIntent();
			Bundle extras = i.getExtras();
			i = new Intent(getApplicationContext(), c);
			i.putExtras(extras);
			startActivity(i);

			finish();
		} catch (ClassNotFoundException e){
			e.printStackTrace();
		}
	}

	/**
	 * This method restricts the user from pressing back to go back to the previous view and forces them to use the cancel button
	 * instead
	 */
	public void onBackPressed() {
		return;
	}

	public void setUpTags(){
		tags.add("" + tagBook.isChecked());
		tags.add("" + tagElectronic.isChecked());
		tags.add("" + tagPersonal.isChecked());
	}
}
